package com.cyf.filmDownload.okhttp;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpUtil {

    private static OkHttpClient okHttpClient;

    static {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new RandomHeaderInterceptor())
                .build();
    }

    private static class RandomHeaderInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            // 生成随机请求头
            Request requestWithHeaders = originalRequest.newBuilder()
                    .header("User-Agent", UserAgentUtil.randomUserAgent())
                    .build();

            return chain.proceed(requestWithHeaders);
        }
    }

    public static Response get(String url) {
        try {
            Request request = new Request.Builder().url(url).get().build();
            return okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}